package com.lanyou.esb.web.serviceManagement;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Part;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.common.CommonUtils;
import com.lanyou.esb.exception.BundleActionException;
import com.lanyou.esb.service.BaseServiceManagementService;
import com.lanyou.esb.servicemix.bean.Bundle;
import com.lanyou.esb.servicemix.monitor.rest.bean.Property;
import com.lanyou.esb.util.FileUploadCilent;
import com.lanyou.esb.web.param.BaseServiceManagementParam;

/**
 * 基础服务管理控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/baseServiceManagement")
public class BaseServiceManagementController {
	@Autowired
	private BaseServiceManagementService baseServiceManagementService;

	@Autowired
	private ResourceLoader resourceLoader;
	@Autowired
	private ParamSettingReppository paramSettingReppository;
	@Autowired
	private UserSessionService userSessionService;

	/**
	 * 查找Bundle,分页
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 * @throws BundleActionException
	 */
	@RequestMapping("/findBundleInfos")
	public Page<Bundle> findBundleInfos(BaseServiceManagementParam param,
			Pageable pageable) throws BundleActionException {

		return baseServiceManagementService.findBundleInfos(param, pageable);

	}

	/**
	 * 启动Bundle
	 * 
	 * @param bundleId
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	@RequestMapping(value = "/startBundle", produces = "application/json")
	public String startBundle(String bundleId) throws HttpException,
			IOException, URISyntaxException {
		Map<String, Object> result = new HashMap<>();
		try {
			baseServiceManagementService.startBundle(bundleId);
			result.put(CommonUtils.MSG_FIELD_RESULT, true);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, false);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}

	/**
	 * 停止Bundle
	 * 
	 * @param bundleId
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	@RequestMapping(value = "/stopBundle", produces = "application/json")
	public String stopBundle(String bundleId) throws HttpException,
			IOException, URISyntaxException {
		Map<String, Object> result = new HashMap<>();
		try {
			baseServiceManagementService.stopBundle(bundleId);
			result.put(CommonUtils.MSG_FIELD_RESULT, 1);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, 0);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}

	/**
	 * 卸载Bundle
	 * 
	 * @param bundleId
	 * @return
	 * @throws HttpException
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	@RequestMapping(value = "/uninstallBundle", produces = "application/json")
	public String uninstallBundle(String bundleId) throws HttpException,
			IOException, URISyntaxException {
		Map<String, Object> result = new HashMap<>();
		try {
			baseServiceManagementService.uninstallBundle(bundleId);
			result.put(CommonUtils.MSG_FIELD_RESULT, 1);
		} catch (Exception e) {
			result.put(CommonUtils.MSG_FIELD_RESULT, 0);
			result.put(CommonUtils.MSG_FIELD_MSG, e.getMessage());
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}

	/**
	 * 查找Bundle详细信息
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 */
	@RequestMapping("/findBundleDetail")
	public Page<Bundle> findBundleDetail(BaseServiceManagementParam param,
			Pageable pageable) {
		int id = -1;
		try {
			id = Integer.parseInt(param.getBundleId());
			Bundle bundle = baseServiceManagementService.getBundleById(id);
			// 过虑无用的属性
			if (bundle.getProps() != null) {
				List<Property> props = bundle.getProps();
				for (int i = props.size() - 1; i >= 0; i--) {
					if (CommonUtils.BUNDLE_PROPS_REMOVE.equals(props.get(i)
							.getKey())) {
						props.remove(i);
					}
				}
			}
			List<Bundle> list = new ArrayList<Bundle>(1);
			list.add(bundle);
			return new PageImpl<Bundle>(list, pageable, 1);
		} catch (Exception e) {
			return new PageImpl<Bundle>(new ArrayList<>(0), pageable, 0);
		}

	}

	/**
	 * 安装或更新Bundle
	 * 
	 * @param name
	 * @param file
	 * @param start
	 * @param startLevel
	 * @return
	 */
	@RequestMapping(value = "/installOrUpdateBundle", method = RequestMethod.POST, produces = "text/plain")
	public String installOrUpdateBundle(@RequestParam("name") String name,
			@RequestParam("file") Part file,
			@RequestParam("start") boolean start,
			@RequestParam("startLevel") String startLevel) {
		// String fileName = file.getName();
		/*if (StringUtils.isBlank(name)) {
			return "文件名不能为空";
		}
		String result = "";
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVER_HANDLE_BUNDLE_PATH);
		if (paramSettingServer == null) {
			return "ServiceMix服务节点配置信息缺失！";
		}
		JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
				.parse(paramSettingServer.getParamValue()).getAsJsonArray();
		if (jsonDatas == null) {
			return "ServiceMix服务节点配置信息缺失！";
		}
		// 测试上传地址是否存在
		for (JsonElement jsonElement : jsonDatas) {
			String filePath = jsonElement.getAsJsonObject().get("uploadServer")
					.getAsString();
			File testFile = new File(filePath);
			if (!testFile.exists()) {
				result = "上传接口部署包的地址：" + filePath + " 不存在！";
				return result;
			}
		}

		String fname = file.getSubmittedFileName();
		String fileName = "";

		if (fname.lastIndexOf("\\") != -1) {
			fileName = fname.substring(fname.lastIndexOf("\\") + 1,
					fname.length());
		} else {
			fileName = fname;
		}
		String path = "";
		File bundleFile = null;
		try {
			for (JsonElement jsonData : jsonDatas) {
				path = jsonData.getAsJsonObject().get("uploadServer")
						.getAsString()
						+ fileName;
				bundleFile = new File(path);
				if (!bundleFile.exists()) {
				} else {
					bundleFile.delete();
				}
				bundleFile.createNewFile();
				InputStream ios = null;
				FileOutputStream fos = null;
				try {
					ios = file.getInputStream();
					fos = new FileOutputStream(bundleFile);
					byte[] b = new byte[(int) file.getSize()];
					while ((ios.read(b)) != -1) {
						fos.write(b);
					}
					fos.flush();
					if (bundleFile.length() <= 0) {
						return "文件不能为空";
					}
				} catch (Exception e) {
				} finally {
					try {
						if (ios != null) {
							ios.close();
						}
					} catch (Exception e) {
					}
					try {
						if (fos != null) {
							fos.close();
						}
					} catch (Exception e) {
					}
				}
			}*/
		
		String result = "";
		try {
			// JsonObject result = new JsonObject();
			ParamSetting paramSettingServer = paramSettingReppository.findByParamName(Constants.SERVERMIX_SERVER);
			// TODO
			if (paramSettingServer == null) {
				result = "上传服务器的ip地址未配置！";
				return result;
			}
			JsonArray jsonDatas = GsonUtil.getDefaultJsonParser().parse(paramSettingServer.getParamValue())
					.getAsJsonArray();
			String fname = file.getSubmittedFileName();
			String fileName = "";
			if (fname.lastIndexOf("\\") != -1) {
				fileName = fname.substring(fname.lastIndexOf("\\") + 1, fname.length());
			} else {
				fileName = fname;
			}
			for (JsonElement jsonElement : jsonDatas) {
				String ip = jsonElement.getAsJsonObject().get("ip").getAsString();
				String socketUploadPort = jsonElement.getAsJsonObject().get("SocketUploadPort").getAsString();
				if (!FileUploadCilent.uploadBundleBySocket(ip, socketUploadPort, fileName, file)) {
					result = "上传接口部署包到 【ip=" + ip + "】 这台服务器上失败！";
					return result;
				}
			}
			// 安装BUNDLE
			baseServiceManagementService.installOrUpdateBundle(fileName, start, startLevel);
			result = "1=操作成功";
		} catch (Exception e) {
			result = e.getMessage();
		} finally {
		}
		return result;
	}
}
